<?php

namespace App\Http\Controllers;

use App\Channel\Russia;
use App\Channel\Wyvn;
use App\Constant;
use App\Events\RechargeComplete;
use App\Models\BalanceLogModel;
use App\Models\PaylogModel;
use App\Utility\PayfastUtility;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use App\Models\SellerWithdrawRequest;
use Auth;
use Illuminate\Support\Facades\DB;
use Session;
use App\Models\Wallet;
use App\Utility\PayhereUtility;

class WalletController extends Controller
{
    public function index()
    {
        $seller_withdraw_requests = SellerWithdrawRequest::where('user_id', Auth::user()->id)->latest()->paginate(15);
        $wallets = Wallet::where('user_id', Auth::user()->id)->latest()->paginate(9);

        return view('frontend.user.wallet.index', compact('wallets', 'seller_withdraw_requests'));
    }

    public function recharge(Request $request)
    {
        $data['amount'] = $request->amount;
        $data['payment_method'] = $request->payment_option;

        // dd($data);

        $request->session()->put('payment_type', 'wallet_payment');
        $request->session()->put('payment_data', $data);

        if ($request->payment_option == 'paypal') {
            $paypal = new PaypalController;
            return $paypal->getCheckout();
        } elseif ($request->payment_option == 'stripe') {
            $stripe = new StripePaymentController;
            return $stripe->stripe();
        } elseif ($request->payment_option == 'mercadopago') {
            $mercadopago = new MercadopagoController;
            return $mercadopago->paybill();
        } elseif ($request->payment_option == 'toyyibpay') {
            $toyyibpay = new ToyyibpayController;
            return $toyyibpay->createbill();
        } elseif ($request->payment_option == 'sslcommerz') {
            $sslcommerz = new PublicSslCommerzPaymentController;
            return $sslcommerz->index($request);
        } elseif ($request->payment_option == 'instamojo') {
            $instamojo = new InstamojoController;
            return $instamojo->pay($request);
        } elseif ($request->payment_option == 'razorpay') {
            $razorpay = new RazorpayController;
            return $razorpay->payWithRazorpay($request);
        } elseif ($request->payment_option == 'paystack') {
            $paystack = new PaystackController;
            return $paystack->redirectToGateway($request);
        } elseif ($request->payment_option == 'voguepay') {
            $voguepay = new VoguePayController;
            return $voguepay->customer_showForm();
        } elseif ($request->payment_option == 'payhere') {
            $order_id = rand(100000, 999999);
            $user_id = Auth::user()->id;
            $amount = $request->amount;
            $first_name = Auth::user()->name;
            $last_name = 'X';
            $phone = '123456789';
            $email = Auth::user()->email;
            $address = 'dummy address';
            $city = 'Colombo';

            return PayhereUtility::create_wallet_form($user_id, $order_id, $amount, $first_name, $last_name, $phone, $email, $address, $city);
        } elseif ($request->payment_option == 'payfast') {
            $user_id = Auth::user()->id;
            $amount = $request->amount;
            return PayfastUtility::create_wallet_form($user_id, $amount);
        } elseif ($request->payment_option == 'ngenius') {
            $ngenius = new NgeniusController();
            return $ngenius->pay();
        } else if ($request->payment_option == 'iyzico') {
            $iyzico = new IyzicoController();
            return $iyzico->pay();
        } else if ($request->payment_option == 'nagad') {
            $nagad = new NagadController;
            return $nagad->getSession();
        } else if ($request->payment_option == 'bkash') {
            $bkash = new BkashController;
            return $bkash->pay();
        } else if ($request->payment_option == 'aamarpay') {
            $aamarpay = new AamarpayController;
            return $aamarpay->index();
        } else if ($request->payment_option == 'mpesa') {
            $mpesa = new MpesaController();
            return $mpesa->pay();
        } else if ($request->payment_option == 'flutterwave') {
            $flutterwave = new FlutterwaveController();
            return $flutterwave->pay();
        } else if ($request->payment_option == 'authorizenet') {
            $authorize_net = new AuthorizeNetController();
            return $authorize_net->pay();
        } elseif ($request->payment_option == 'payku') {
            return (new PaykuController)->create($request);
        }
    }

    public function wallet_payment_done($payment_data, $payment_details)
    {
        $user = Auth::user();
        $user->balance = $user->balance + $payment_data['amount'];
        $user->save();

        $wallet = new Wallet;
        $wallet->user_id = $user->id;
        $wallet->amount = $payment_data['amount'];
        $wallet->payment_method = $payment_data['payment_method'];
        $wallet->payment_details = $payment_details;
        $wallet->save();

        Session::forget('payment_data');
        Session::forget('payment_type');

        flash(translate('Payment completed'))->success();
        return redirect()->route('wallet.index');
    }

    public function offline_recharge(Request $request)
    {
        /*if ($request->amount < 200) {
            flash(translate('The recharge amount must be greater than 200 less than 100000'))->error();
            return back();
        }*/
        $post = $request->post();
        DB::beginTransaction();
        $trade_no = get_trade_no();
        $wallet = new Wallet;
        
        if($request->payment_option == 'MOMO' || $request->payment_option == 'ZALO' || $request->payment_option == 'VTPAY'){
            $wallet->amount = $request->amount/23723;
        }else{
            $wallet->amount = $request->amount;
        }
        
        $wallet->user_id = Auth::user()->id;
        //$wallet->amount = $request->amount;
        $wallet->payment_method = $request->payment_option;
        $wallet->payment_details = $request->trx_id;
        $wallet->approval = 0;
        //$wallet->offline_payment = $wallet->payment->type == 'custom_payment' ? 0:1; 
        $wallet->offline_payment = 1;
        $wallet->reciept = $request->photo;
        $wallet->no = $trade_no;
        $wallet->type = $post['is_deposit'] ? 'deposit' : 'balance';
        $wallet->save();
//        flash(translate('Offline Recharge has been done. Please wait for response.'))->success();
//        return redirect()->route('wallet.index');

        $paylog_model = PaylogModel::create([
            'trade_no' => $trade_no,
            'user_id' => $wallet->user_id,
            'description' => $post['is_deposit'] ? "Deposit Recharge" : 'Wallet Recharge',
            'money' => $wallet->amount,
            'relate_type' => $post['is_deposit'] ? Constant::PAYLOG_TYPE_DEPOSIT : Constant::PAYLOG_TYPE_RECHARGE,
            'relate_id' => $wallet->id
        ]);
        DB::commit();

        if($wallet->payment->type == 'custom_payment') {
            if($request->payment_option == 'MOMO' || $request->payment_option == 'ZALO' || $request->payment_option == 'VTPAY'){
            $wy = new Wyvn;
            //echo '----调用充值功能888------';
            $result = $wy->chargeforuser($paylog_model->money, $paylog_model->trade_no, $request->payment_option);
        }else{
            $re = new Russia();
            //echo '----调用充值功能888------';
            $result = $re->chargeforuser($paylog_model->money, $paylog_model->trade_no, $request->payment_option);
        }
            
            
            return redirect($result);
        } else {
            flash(translate('Offline Recharge has been done. Please wait for response.'))->success();
            return redirect()->route('wallet.index');
        }
    }

    public function offline_recharge_request(Request $request)
    {
        $status = $request->input('approval', -1);
        $search = $request->input('search');
        $wallets = Wallet::whereHas('user', function ($query) use ($search) {
            if(!empty($search)) {
                $query->where('email', 'like', '%'. $search . '%')->orWhere('name', 'like', '%'. $search . '%');
            }
        })->when($status > -1, function ($query) use ($status) {
            $query->where('approval', $status);
        })->where('offline_payment', 1)->orderBy('id', 'desc')->paginate(10);

        return view('manual_payment_methods.wallet_request', compact('wallets'));
    }

    public function updateApproved(Request $request)
    {
        $wallet_model = Wallet::findOrFail($request->id);
        $wallet_model->approval = $request->status;
        if ($request->status == 1) {
            $user_model = $wallet_model->user;
            if($wallet_model->type == 'balance') {
                $balance_log_model = BalanceLogModel::create([
                    'user_id' => $user_model->id,
                    'type' => Constant::BALANCE_LOG_TYPE_RECHARGE,
                    'value_before' => $user_model->balance,
                    'value' => $wallet_model->amount,
                    'description' => "Recharge",
                    'trade_id' => $wallet_model->id,
                ]);

                $user_model->balance = $user_model->balance + $wallet_model->amount;
                $user_model->save();
                event(new RechargeComplete($wallet_model->paylog));
            } elseif ($wallet_model->type == 'deposit') {
                $user_model->deposit = $user_model->deposit + $wallet_model->amount;
                $user_model->save();
            }


        }
        if ($wallet_model->save()) {
            return 1;
        }
        return 0;
    }
}
